<!-- 负责人管理 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="96px">
      <el-form-item :label="v.name" :prop="v.prop" v-for="v in searchItems">
        <el-input v-if="v.type == 'input'" v-model="queryParams[v.prop]" :placeholder="'请输入' + v.name" clearable
          @keyup.enter="handleQuery" />
        <el-tree-select v-else-if="v.type == 'treeSelect'" v-model="queryParams[v.prop]" :placeholder="'请选择' + v.name"
          clearable :data="sel_option[v.prop]" :expand-on-click-node="false" :render-after-expand="false"
          @change="handleQuery" check-strictly :props="{ label: 'label' }" node-key="id" filterable />
        <el-date-picker v-else-if="v.type == 'dateTime'" v-model="queryParams[v.prop]" value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange" :default-time="[new Date(2000, 1, 1, 0, 0, 0),
          new Date(2000, 2, 1, 23, 59, 59),]" range-separator="-" start-placeholder="开始时间"
          end-placeholder="结束时间"></el-date-picker>
        <el-date-picker v-else-if="v.type == 'date'" v-model="queryParams[v.prop]" value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="[new Date(2000, 1, 1, 0, 0, 0),
          new Date(2000, 2, 1, 23, 59, 59),]" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期"></el-date-picker>
        <el-select v-else-if="v.type == 'select'" v-model="queryParams[v.prop]" clearable filterable
          :placeholder="'请输入' + v.name" @change="handleQuery">
          <el-option v-for="item in sel_option[v.prop]" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['comlbs:driverInfo:add']">新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['comlbs:driverInfo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['comlbs:driverInfo:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table highlight-current-row v-loading="loading" :data="driverInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column :label="v.name" align="left" :prop="v.prop" v-for="v in tableItems" :width="v.width">
        <template #default="scope">
          <dict-tag v-if="v.type == 'dict'" :options="sel_option[v.prop]" :value="scope.row[v.prop]" />
          <el-image v-else-if="v.prop == 'picture'" :src="getImgSrc(scope.row[v.prop])" style="width:40px;height:40px">
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <!-- <PictureFilled /> -->
                </el-icon>
              </div>
            </template>
          </el-image>
          <span v-else>{{ scope.row[v.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="210" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Document" @click="handleDetail(scope.row)"
            v-hasPermi="['comlbs:driverInfo:edit']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['comlbs:driverInfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-if="!scope.row.bindStatus"
            v-hasPermi="['comlbs:driverInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改负责人信息对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body class="sky-form">
      <el-form ref="driverInfoRef" :model="form" :rules="rules" label-width="100px" :inline="true" :disabled="disabled">
        <el-form-item v-for="v in driverItem" :key="v.prop" :label="v.name" :prop="v.prop" :class="v.type">
          <el-input v-if="v.type == 'input'" v-model.trim="form[v.prop]" :disabled="v.prop == 'numberPlate'"></el-input>
          <el-select v-else-if="v.type == 'select'" v-model="form[v.prop]" filterable clearable>
            <el-option v-for="item in sel_option[v.prop]" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-tree-select v-else-if="v.type == 'treeSelect'" v-model="form[v.prop]" clearable :data="sel_option[v.prop]"
            :expand-on-click-node="false" :render-after-expand="false" check-strictly :props="{ label: 'label' }"
            node-key="id" filterable placeholder="" />
          <ImageUpload :limit="1" :rank="0" ref="driverUploadPic" url='/comlbs/driverInfo/uploadFile'
            style="height: 148px;" :pictures='form.picture || []' :disabled="disabled" v-else-if="v.type == 'photo'">
          </ImageUpload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="!disabled">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DriverInfo">
import dayjs from "dayjs"
import { listDriverInfo, getDriverInfo, delDriverInfo, addDriverInfo, updateDriverInfo } from "@/api/comlbs/driverInfo";
import { treeDept } from "@/api/system/dept";
const { proxy } = getCurrentInstance();
function myRequire(str) {
  return new URL(`../../../assets/img/${str}`, import.meta.url).href
}

const driverInfoList = ref([]);
const open = ref(false);
const disabled = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 15,
  },
  rules: {
    name: [{ required: true, message: "请输入负责人姓名", trigger: "blur" },],
  }
});
const searchItems = ref([
  { name: '负责人姓名', prop: "name", type: 'input' },
  { name: '所属公司', prop: "companyId", type: 'treeSelect' },
  { name: '监管对象名称', prop: "numberPlate", type: 'input' },
]);
const tableItems = ref([
  { name: '负责人姓名', prop: 'name', width: '150' },
  { name: '所属公司', prop: 'companyName' },
  { name: '绑定监管对象', prop: 'numberPlate' },
  { name: '身份证号', prop: 'idCard' },
  { name: '联系方式', prop: 'contactNumber' },
  { name: '年龄', prop: 'age', width: '100' },
  { name: '图片附件', prop: 'picture', width: '100' },
  { name: '创建时间', prop: "createTime" },
])
// 负责人信息
const driverItem = ref([
  { name: '负责人姓名', prop: 'name', type: 'input' },
  { name: '所属公司', prop: 'companyId', type: 'treeSelect' },
  { name: '绑定监管对象', prop: 'numberPlate', type: 'input' },
  { name: '身份证号', prop: 'idCard', type: 'input' },
  { name: '联系方式', prop: 'contactNumber', type: 'input' },
  { name: '年龄', prop: 'age', type: 'input' },
  { name: '图片附件', prop: 'picture', type: 'photo' },
])
const sel_option = ref({});

let dictList = tableItems.value.filter(v => v.type == 'dict').map(v => v.prop);
sel_option.value = proxy.useDict.apply(this, [...dictList, "checkStatus", "deviceModel", "channels"]);
const { queryParams, form, rules } = toRefs(data);
treeDept().then(res => {
  sel_option.value.companyId = res.data
})

function getImgSrc(list) {
  if (Array.isArray(list) && list.length > 0) {
    return import.meta.env.VITE_APP_BASE_API + list[0].path;
  }
  else return "";
}

/** 查询负责人信息列表 */
function getList() {
  loading.value = true;
  listDriverInfo(queryParams.value).then(response => {
    driverInfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    companyId: null,
    name: null,
    contactNumber: null,
    idCard: null,
    sex: null,
    licenseType: null,
    licenseNum: null,
    driverAge: null,
    picture: null,
    gmtCreate: null,
    gmtModified: null,
    modifiedUserId: null,
    createUserId: null,
    age: null
  };
  proxy.resetForm("driverInfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  disabled.value = false;
  open.value = true;
  title.value = "添加负责人";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  disabled.value = false;
  const _id = row.id || ids.value
  getDriverInfo(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改负责人";
  });
}

/** 详情按钮操作 */
function handleDetail(row) {
  reset();
  const _id = row.id || ids.value
  getDriverInfo(_id).then(response => {
    form.value = response.data;
    open.value = true;
    disabled.value = true;
    title.value = "负责人详情";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["driverInfoRef"].validate(async valid => {
    if (valid) {
      if (form.value.id != null) {
        form.value.picture = await proxy.$refs["driverUploadPic"][0]?.uploadInfo();
        updateDriverInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDriverInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  let length = row.id ? 1 : _ids.length
  proxy.$modal.confirm('是否确认删除这' + length + '项数据？').then(function () {
    return delDriverInfo(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comlbs/driverInfo/export', {
    ...queryParams.value
  }, `负责人管理_${dayjs(new Date()).format("YYYY-MM-DD_HH:mm:ss")}.xlsx`)
}

getList();
</script>
